package uit.edu.vn.Activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import uit.edu.vn.Model.myFile;
import uit.edu.vn.Utility.FileListAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FileActivity extends ListActivity{
	 //private List<String> item1 = null;
	 private List<myFile> myItem = null;
	 private List<String> path = null;
	 private AlertDialog.Builder builder;
	 private Handler handler;
	 private ProgressDialog loadingFileDialog;
	 private Resources res;
	 private TextView myPath;
	 private ListView fileList;
	 private FileListAdapter fAdapter;
	 private String root="/sdcard";
	 private ArrayList<Boolean> itemFileCheck=new  ArrayList<Boolean>(); 
	 private ArrayList<String> itemFileString= new ArrayList<String>(); 
	 private final int menu_Logout=0;
	 private final int menu_Backup=1;
	 private final int menu_MarkAll=2;
	 Thread myFileThread;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.backup_file);
		 res=getResources();
	     fileList=getListView();
	     builder= new AlertDialog.Builder(this);
	     myPath= (TextView)findViewById(R.id.txt_filePath);
		
	   //goi dialog
		 loadingFileDialog = ProgressDialog.show(FileActivity.this, "","Đang Tải Dữ Liệu ...", true);
		
	  
	     // xu ly su kien click
		 
	     
		// tao thread backgroundthread tach roi voi UI
		 handler= new Handler();
		  myFileThread= new Thread(null,BackGroundThread,"File Background");
		 myFileThread.start(); 
		 getDir(root);
	}
	//ham xu ly thread
	public Runnable BackGroundThread = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			doinBackGround();
		}
	};
	private void doinBackGround()
	{

		 handler.post(doUpdateUI);
	}
	public Runnable doUpdateUI = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			//updateGUI();
			loadingFileDialog.dismiss();
		
		}
	};
	private void updateGUI()
	{
		//test custom adapter 
		fAdapter = new FileListAdapter( getBaseContext(),myItem);
    	setListAdapter(fAdapter);
	    itemFileCheck = fAdapter.getCheckList(); 
    	//lay gia tri mang itemcheck
    	
	}	
	// ham xu ly chinh
	private void getDir(String dirPath)
    {
    	// gán dường dẫn vào text view 
    	myPath.setText("Location: " + dirPath);
    	myItem = new ArrayList<myFile>();
    	//path để lưu đường dẫn
    	path = new ArrayList<String>();
    	File f = new File(dirPath);
    	//liệt kê danh sách các file 
    	File[] files = f.listFiles();
    	// sap xep theo anpha ,beta
    	Arrays.sort(files);
    	if(!dirPath.equals(root))
    	{
    		//item.add(new myFile(root, res.getDrawable(R.drawable.ic_file_selector)));
    		//path.add(root);
    		myItem.add(new myFile("../","", res.getDrawable(R.drawable.ic_back)));
    		path.add(f.getParent());          
    	}
    	for(int i=0; i < files.length; i++)
    	{
    		File file = files[i];
    		path.add(file.getPath()); 	
    		if(file.isDirectory())
    		{
    			myItem.add(new myFile(file.getName(),file.getPath() , res.getDrawable(R.drawable.ic_file_selector)));
    		}
    		else 
    		{
    			String nameFile=file.getName().toLowerCase();
    			if(nameFile.endsWith("mp3"))
    			{
    				myItem.add(new myFile(file.getName(),file.getPath(), res.getDrawable(R.drawable.ic_music_selector)));
    		    	
    			}
    			else if(nameFile.endsWith("png")||nameFile.endsWith("jpg"))
    			{
    				myItem.add(new myFile(file.getName(),file.getPath(), res.getDrawable(R.drawable.ic_image_selector)));
    		    	
    			}
    			else
    			{
    				myItem.add(new myFile(file.getName(), file.getPath(),res.getDrawable(R.drawable.ic_text)));
    			}
    		}
    	}  	
    	fileList.setOnItemClickListener(new OnItemClickListener() 
    	{
		 @Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
    				long arg3) {
    			// TODO Auto-generated method stub
    			File file =new File(path.get(position));
    	    	if(file.isDirectory())
    	    	{
    	    		if(file.canRead())
    	    		{
    	    			getDir(path.get(position));
    	    	    	
    	    		}
    	    		else
    	    		{
    	    			builder.setMessage("Ban Khong The Mo File Nay").setCancelable(false).setPositiveButton("yes",new OnClickListener() {
    						
    						@Override
    						public void onClick(DialogInterface dialog, int which) {
    							// TODO Auto-generated method stub
    							FileActivity.this.finish();
    						}
    					})
    	    			.setNegativeButton("No", new OnClickListener() {
    						
    						@Override
    						public void onClick(DialogInterface dialog, int which) {
    							// TODO Auto-generated method stub
    							dialog.cancel();
    						}
    					});
    	    			AlertDialog alert = builder.create();
    	    		}
    	    	}
    		}
		});
    	fAdapter = new FileListAdapter( getBaseContext(),myItem);
    	setListAdapter(fAdapter);
	    itemFileCheck = fAdapter.getCheckList(); 
    }
    public boolean onCreateOptionsMenu(Menu menu) {
    	// TODO Auto-generated method stub
    	//return super.onCreateOptionsMenu(menu);
    	 menu.add(0, menu_Logout, 3,"Đăng Xuất").setIcon(R.drawable.ic_launcher);
    	 menu.add(0, menu_Backup, 2,"Sao Lưu").setIcon(R.drawable.ic_launcher);
    	 menu.add(0, menu_MarkAll,1, "Chon Hết").setIcon(R.drawable.ic_launcher);
		return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// TODO Auto-generated method stub
    	switch(item.getItemId())
    	{
    		case menu_Backup:
    			//xu ly backup
    			itemFileString.clear();
    			String temp= null;
    			for(int i=0;i<itemFileCheck.size();i++)
    			{
    				// kiem tra mang item check , neu la
    				//true thi lay vi tri va truyen vao 
    				//cursor
    				if(itemFileCheck.get(i)==true)
    				{
    					Log.d("i","co check");
    					temp=myPath.getText()+myItem.get(i).getNameFile();
    				}				
    			}
    			
    			showToast(temp);
    			return true;
    		case menu_Logout:
    			//xu ly logout
    			finish();
    			return true;
    		case menu_MarkAll:
    			//xu ly check all
    			for(int i=0;i<itemFileCheck.size();i++)
    		       {
    				  itemFileCheck.set(i, true);
    		    	  fAdapter.setCheckList(itemFileCheck);    		    	  
    		       }
    			this.setListAdapter(fAdapter);
    			return true;
    	}
    	return false;
    }   
    public void showToast(String message)
    {
		Toast.makeText(this,message , Toast.LENGTH_SHORT).show();
    }
}
